from rest_framework_simplejwt.tokens import AccessToken, SlidingToken, RefreshToken
from datetime import datetime
from django.test import TestCase
from rest_framework_simplejwt.settings import api_settings
from django.contrib.auth import get_user_model


def get_token_remaining_time(token_str) -> int:
    """
    获取token剩余时间
    """
    try:
        access_token = AccessToken(token_str)
        access_token.verify()
        # 获取JWT令牌中的参数
        # 获取过期时间戳（秒）
        exp_timestamp = access_token["exp"]
        # JWT令牌的签发时间。
        issued_at = access_token["iat"]
        print(f"JWT令牌的签发时间:{issued_at}")

        remaining_seconds = exp_timestamp - datetime.now().timestamp()

        if remaining_seconds > 0:
            print(f"Token 剩余时间：{int(remaining_seconds)} 秒")
            # 转为分钟
            remaining_minutes = remaining_seconds / 60
            print(f"Token 剩余时间：{int(remaining_minutes)} 分钟")
        else:
            print("Token 已过期")
        return int(remaining_seconds)
    except Exception as e:
        print(f"Token 解析失败: {e}")


def get_token_remaining_time_sliding(token_str) -> int:
    """
    获取token剩余时间
    """
    try:
        access_token = SlidingToken(token_str)
        access_token.verify()
        # 获取JWT令牌中的参数
        # 获取过期时间戳（秒）
        exp_timestamp = access_token["exp"]
        # JWT令牌的签发时间。
        issued_at = access_token["iat"]
        print(f"JWT令牌的签发时间:{issued_at}")

        remaining_seconds = exp_timestamp - datetime.now().timestamp()

        if remaining_seconds > 0:
            print(f"Token 剩余时间：{int(remaining_seconds)} 秒")
            # 转为分钟
            remaining_minutes = remaining_seconds / 60
            print(f"Token 剩余时间：{int(remaining_minutes)} 分钟")
        else:
            print("Token 已过期")
        return int(remaining_seconds)
    except Exception as e:
        print(f"Token 解析失败: {e}")


def refresh_tokens_directly(refresh_token_str: str):
    """
    直接使用 RefreshToken 类刷新令牌
    Args:
        refresh_token_str: 有效的刷新令牌字符串
    Returns:
        tuple: (新访问令牌, 新刷新令牌)
    """
    try:
        # 验证并创建 RefreshToken 实例
        refresh_token = RefreshToken(token=refresh_token_str)
        refresh_token.verify()
        # 获取新访问令牌
        new_access = str(refresh_token.access_token)

        # 获取用户ID（从令牌中提取）
        user_id = refresh_token[api_settings.USER_ID_CLAIM]
        User = get_user_model()
        user = User.objects.get(id=user_id)

        # 生成新的刷新令牌
        new_refresh = str(RefreshToken.for_user(user))

        # 打印
        print(f"New Access Token: {new_access}")
        print(f"New Refresh Token: {new_refresh}")

        return new_access, new_refresh

    except Exception as e:
        print(f"令牌刷新失败: {e}")
        raise


class TokenParseTest(TestCase):

    # def test_valid_token(self):
    #     """
    #     测试token解析
    #     python .\manage.py test chat_app.jwt.token_parse
    #     """
    #     token_str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzUxOTY1MDk0LCJpYXQiOjE3NTE5NjUwMzQsImp0aSI6ImMwODkyMTVhZWZkYTRkMGVhYTU3M2Y5MzZlYjI5ZDlkIiwidXNlcl9pZCI6Mn0.KRRzww0n5O5VHpSM9px1hmRrzHhtXKYuFWRvM6Nupyc"

    #     get_token_remaining_time(token_str)

    def test_refresh_tokean(self):
        token_str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTc1MjA1MzIxNCwiaWF0IjoxNzUxOTY2ODE0LCJqdGkiOiJkZjMzMGVlN2Y0MTk0Mjc3YjAxZWIwYTQ0ZDE1NjE4ZSIsInVzZXJfaWQiOjJ9.ZYftMtG4QAKNrTUPESHG2c6IOSq9G5KGrkMQKGgIDoY"
        refresh_tokens_directly(token_str)
